﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	CamlQueryBuilderGroupBy.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Linq;

namespace Smart.Common.Entities
{
	/// <summary>
	/// GroupBy group
	/// </summary>
	public class CamlQueryBuilderGroupBy<TExecutorType> : CamlQueryBuilderItemGroupGroupable<TExecutorType>, IQueryBuilderGroupBy<TExecutorType>
		where TExecutorType : class
	{
		/// <summary>
		/// Collapse groups or not
		/// </summary>
		public bool Collapse { get; set; }

		/// <summary>
		/// Group limit on one page
		/// </summary>
		public int GroupLimit { get; set; }

		public CamlQueryBuilderGroupBy()
			: base("GroupBy", false, true)
		{
			Collapse = true;
			GroupLimit = 100;
		}

		/// <summary>
		/// Set GroupBy options
		/// </summary>
		public IQueryBuilderGroupBy<TExecutorType> Set(bool collapse, int groupLimit)
		{
			this.Collapse = collapse;
			this.GroupLimit = groupLimit;

			return this;
		}

		/// <summary>
		/// Set GroupBy options
		/// </summary>
		public IQueryBuilderGroupBy<TExecutorType> Set(int groupLimit)
		{
			this.GroupLimit = groupLimit;

			return this;
		}

		/// <summary>
		/// Set GroupBy options
		/// </summary>
		public IQueryBuilderGroupBy<TExecutorType> Set(bool collapse)
		{
			this.Collapse = collapse;

			return this;
		}

		/// <summary>
		/// Add group by <paramref name="field"/>
		/// </summary>
		public IQueryBuilderGroupBy<TExecutorType> Field(string field)
		{
			AddItem(new CamlQueryBuilderGroupItem<TExecutorType>(field));

			return this;
		}

		/// <summary>
		/// Return Cache code
		/// </summary>
		public override int GetCacheCode()
		{
			return
				base.GetCacheCode() ^ (Collapse.GetHashCode() << 8) ^ (GroupLimit.GetHashCode() << 2);
		}

		/// <summary>
		/// Format QueryBuilder statement
		/// </summary>
		public override string FormatQuery()
		{
			var expr = Children.Where(item => item != null).CastToString(string.Empty, item => item.FormatQuery());

			return
				expr.IsNullOrEmpty()
					? string.Empty
					: string.Format("<{0} Collapse=\"{1}\" GroupLimit=\"{2}\" >{3}</{0}>", Op, (Collapse ? "TRUE" : "FALSE"), GroupLimit, expr);
		}
	}
}